﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace game
{
    /// <summary>
    /// Safe Add-Remove List
    /// Wrapper for the generic collection specified as an argument;
    /// allows to safely add and remove elements from the list WHILE iterating through it,
    /// what is normally prohibited.
    /// Addition (removal) operations simply enqueue objects to objects-to-add-queue
    /// (objects-to-remove-queue) and on the user demand by calling Resolve(),
    /// queues are applied to main list.
    /// </summary>
    /// <typeparam name="T">Type of objects to store</typeparam>
    public class SafeARList<T> : IEnumerable<T>
    {
        protected LinkedList<T> list;
        protected Queue<T> toAdd;
        protected Queue<T> toRemove;

        public SafeARList()
            : this(new LinkedList<T>())
        {
        }

        public SafeARList(LinkedList<T> list)
        {
            if (list == null)
                throw new Exception("SafeIRList : constructor argument == NULL\n");

            this.list = list;

            toAdd = new Queue<T>();
            toRemove = new Queue<T>();
        }

        public void AddDirectly(T element)
        {
            list.AddFirst(element);
        }

        public void Add(T element)
        {
            toAdd.Enqueue(element);
        }

        public void Remove(T element)
        {
            toRemove.Enqueue(element);
        }

        public void Clear()
        {
            list.Clear();
        }

        /// <summary>
        /// If you performed some addition or removal operation and you want
        /// them to be reflected in the current state of the list, call Resolve().
        /// CAUTION: never call it while iterating through collection.
        /// </summary>
        public void Resolve()
        {
            while (toRemove.Count > 0)
            {
                list.Remove(toRemove.Dequeue());
            }

            while (toAdd.Count > 0)
            {
                list.AddFirst(toAdd.Dequeue());
            }
        }

        #region IEnumerable<T> Members

        IEnumerator<T> IEnumerable<T>.GetEnumerator()
        {
            return list.GetEnumerator();
        }

        #endregion

        #region IEnumerable Members

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return list.GetEnumerator();
        }

        #endregion

    }
}
